<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/27 0027
 * Time: 下午 8:12
 */
namespace app\api\service;

use app\admin\model\Store;
use app\admin\model\Ticket;
use app\admin\model\Userconsumedetail;
use app\common\Helper;
use app\admin\model\User;
use app\lib\exception\PayException;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class Pay{

    private $userId;
    private $storeId;
    private $ticketId;
    private $orderId;
    private $orderSource;
    private $total_fee;
    private $receiveticId = NULL;

    function __construct($param)
    {
        $this->userId = $param['userId'];
        $this->storeId = $param['storeId'];
        $this->ticketId = $param['ticketId'];
        $this->orderSource = $param['orderSource'];
        $this->total_fee = $param['total_fee'];
        if(isset($param['receiveticId'])){
            $this->receiveticId = $param['receiveticId'];
        }
    }


    public function pay(){
        if($this->orderSource == 1){
            $TicketModel = new Ticket();
            $ticket = $TicketModel->getTicket($this->ticketId);
            $totalPrice = $ticket->buyTicketMoney;
            $productName = $ticket->name;
        }elseif ($this->orderSource == 2){
            $totalPrice = $this->total_fee;
            $productName = '当面付';
        }else{
            //todo
        }

        return show(config('status.SUCCESS_STATUS'),'ok',$this->makeWxPreOrder($totalPrice,$productName));

    }

    /**
     * 生成微信预订单
     * @param $totalPrice
     * @return array
     */
    private function makeWxPreOrder($totalPrice,$productName){
        $openid = User::getopenId($this->userId);
        $orderNO = $this->makeOrderNo();
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($orderNO);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice);
        $wxOrderData->SetBody($productName);
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url(config('wx.pay_back_url'));

        $orderdata['totalPrice'] = $totalPrice;
        $orderdata['orderNo'] = $orderNO;

        return $this->getPaySignature($wxOrderData,$orderdata);

    }

    /**
     * 请求微信统一下单接口返回给客户端一组支付参数
     * @param $wxOrderData
     * @return \成功时返回，其他抛异常
     */
    private function getPaySignature($wxOrderData,$orderdata){
        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('获取预支付订单失败','error');
        }else{
            //插入预订单(未支付)
            $data['userId'] = $this->userId;
            $data['storeId'] = $this->storeId;
            $data['ticketId'] = $this->ticketId;
            $data['orderNo'] = $orderdata['orderNo'];
            $data['totalPrice'] = $orderdata['totalPrice'];
            $this->insertOrder($data);
        }
        if($wxOrder['return_code'] == 'FAIL'){
            throw new PayException([
                'msg' => '商户号或者支付秘钥异常'
            ]);
        }
        $this->recordPreOrder($wxOrder);
        return $this->sign($wxOrder);
    }

    /**
     * 生成签名
     * @param $wxOrder
     * @return array
     */
    private function sign($wxOrder){
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.app_id'));
        $jsApiPayData->SetTimeStamp((string)time());
        $jsApiPayData->SetNonceStr(Helper::getUUID());
        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');
        $sign = $jsApiPayData->MakeSign();
        $rowValues = $jsApiPayData->GetValues();
        $rowValues['paySign'] = $sign;
        unset($rowValues['appId']);
        return $rowValues;
    }

    private function recordPreOrder($wxOrder){
        Userconsumedetail::where('id','=',$this->orderId)->update(['prepay_id'=>$wxOrder['prepay_id']]);
    }


    private function insertOrder($data){
        $Userconsumedetail = new Userconsumedetail();
        $Userconsumedetail->id = Helper::getUUID();
        $Userconsumedetail->userId = $data['userId'];
        $Userconsumedetail->storeId = $data['storeId'];
        if($this->orderSource == 1){
            $Userconsumedetail->ticketId = $data['ticketId'];
        }
        if($this->orderSource == 2){
            $Userconsumedetail->receiveticId = $this->receiveticId;
        }
        $Userconsumedetail->remittee = $this->getstoreName($data['storeId']);
        $Userconsumedetail->payMoney = $data['totalPrice'];
        $Userconsumedetail->orderNo = $data['orderNo'];
        $Userconsumedetail->orderSource = $this->orderSource;
        $Userconsumedetail->save();
        $this->orderId = $Userconsumedetail->id;
    }

    private function getstoreName($storeId){
        $Store = Store::get($storeId);
        return $Store->name;
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M');
        $orderSn =
            $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }
}